package org.ruizhijie.run;

import gnu.io.CommPortIdentifier;
import gnu.io.SerialPort;
import gnu.io.SerialPortEvent;
import gnu.io.SerialPortEventListener;

import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.ruizhijie.config.SystemConfig;
import org.ruizhijie.i.IPublisher;

public class InCom implements Runnable, SerialPortEventListener {
	private Logger log = LogManager.getLogger(LogManager.ROOT_LOGGER_NAME);
	// 检测系统中可用的通讯端口类
	private CommPortIdentifier cpi;
	// RS232串口
	private SerialPort serialPort;

	// 输入输出流
	private InputStream inputStream;

	private IPublisher publish;
	private String com;

	public InCom(IPublisher publish,String inCom, String outCom) {
		this.publish=publish;
		this.com = inCom;
		this.cpi = getCommPort(inCom);
		

		if (this.cpi == null) {
			log.error(inCom + "获取串口失败, 程序退出");
			System.exit(0);
			return;
		}
		System.err.println(inCom + "获取串口成功");

		try {
			serialPort = (SerialPort) cpi.open("SerialPort_" + inCom, 2000);
			// 设置串口监听
			serialPort.addEventListener(this);
			// 设置串口数据时间有效(可监听)
			serialPort.notifyOnDataAvailable(true);
			// 设置串口通讯参数:波特率，数据位，停止位,校验方式
			serialPort.setSerialPortParams(SystemConfig.baudRate,
					SystemConfig.dataBits,
					SystemConfig.stopBits,
					SystemConfig.parity);
		} catch (Exception e) {
			e.printStackTrace();
			System.exit(0);
		}
	}

	@SuppressWarnings("unchecked")
	private CommPortIdentifier getCommPort(String serialNumber) {
		Enumeration<CommPortIdentifier> portList = CommPortIdentifier
				.getPortIdentifiers();
		while (portList.hasMoreElements()) {
			CommPortIdentifier cpi = portList.nextElement();
			// 判断是否是串口
			if (cpi.getPortType() == CommPortIdentifier.PORT_SERIAL
					&& serialNumber.equals(cpi.getName())) {
				return cpi;
			}
		}
		return null;
	}

	// 实现接口SerialPortEventListener中的方法 读取从串口中接收的数据
	@Override
	public void serialEvent(SerialPortEvent event) {
		switch (event.getEventType()) {
		case SerialPortEvent.BI: // 通讯中断
		case SerialPortEvent.OE: // 溢位错误
		case SerialPortEvent.FE: // 帧错误
		case SerialPortEvent.PE: // 奇偶校验错误
		case SerialPortEvent.CD: // 载波检测
		case SerialPortEvent.CTS: // 清除发送
		case SerialPortEvent.DSR: // 数据设备准备好
		case SerialPortEvent.RI: // 响铃侦测
		case SerialPortEvent.OUTPUT_BUFFER_EMPTY: // 输出缓冲区已清空
			break;
		case SerialPortEvent.DATA_AVAILABLE: // 有数据到达
			readComm();
			break;
		default:
			break;
		}
	}

	// 读取串口返回信息
	public void readComm() {
		try {
			inputStream = serialPort.getInputStream();
			byte[] readBuffer = new byte[inputStream.available()];
			// 从线路上读取数据流
			while (inputStream.read(readBuffer) != -1) {

				// log.info("-"+ConvertUtil.bytesToHexString(readBuffer)+"-");
				// log.info("-----"+new String(readBuffer,"UTF-8")+"-----");

				// this.callback.exec(ConvertUtil.bytesToHexString(readBuffer));
//				this.callback.exec(this.com,new String(readBuffer, "UTF-8"));
				this.publish.publish(com, readBuffer);
				break;
			}
			// closeSerialPort();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public void closeSerialPort() {
		// uniqueInstance.serialPort.close();
	}

	// 向串口发送数据
	// public void sendMsg(){
	// String information = "AT\r";
	// try {
	// //实例化输出流
	// outputStream = serialPort.getOutputStream();
	// } catch (IOException e1) {
	// e1.printStackTrace();
	// }
	// try {
	// outputStream.write(information.getBytes());
	// } catch (IOException e) {
	// e.printStackTrace();
	// }
	// }

	@Override
	public void run() {
		// init();
		// sendMsg();

	}
}
